package com.example.petshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.petshop.entity.Goods;
import com.example.petshop.mapper.GoodsMapper;
import com.example.petshop.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class GoodsServiceImpl implements GoodsService {
    private final GoodsMapper goodsMapper;

    @Autowired
    public GoodsServiceImpl(GoodsMapper goodsMapper) {
        this.goodsMapper = goodsMapper;
    }

    @Override
    public List<Goods> getAll() {
        return goodsMapper.getAll();
    }


    @Override
    public Optional<Goods> getById(Integer goodsId) {
        return goodsMapper.getById(goodsId);
    }

    @Override
    public List<Goods> getGoodsByShopId(Integer shopId) {
        return goodsMapper.findGoodsByShopId(shopId);
    }

    @Override
    public void updateState(Integer goodsId, Integer state) {
        // 检查商品是否存在
        Optional<Goods> goodsOptional = goodsMapper.getById(goodsId);
        if (goodsOptional.isEmpty()) {
            throw new RuntimeException("商品不存在");
        }

        // 获取商品对象
        Goods goods = goodsOptional.get();

        // 更新商品状态
        goods.setState(state);

        // 调用mapper的update方法来更新数据库
        goodsMapper.updateById(goods);
    }

    @Override
    public List<Goods> getByState(int state) {
        return goodsMapper.getByState(state);
    }

    @Override
    public void createGoods(Goods goods) {
        goodsMapper.insert(goods);
    }

    @Override
    public void deleteGoods(Integer goodsId) {
        goodsMapper.deleteById(goodsId);
    }

    @Override
    public void updateGoods(Goods goods) {
        goodsMapper.updateGoods(goods);
    }

    @Override
    public List<Goods> getGoodsByCategory(String category) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_category", category);
        return goodsMapper.selectList(queryWrapper);
    }

    @Override
    public Goods getGoodsByName(String goodsName) {
        return goodsMapper.getGoodsByName(goodsName);
    }

}


